package com.zq.it.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zq.it.tool.Constant;

/**
 * 检测中账户是否已经登录，如果登录则禁止二次登录，否则进入登录主界面
 */

public class ITFilter implements Filter {

	@Override
	public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String basePath = request.getContextPath();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		String pathInfo = request.getRequestURI();
		pathInfo = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);
		if (pathInfo.startsWith("admin_login")
				|| pathInfo.startsWith("securityCode") 
				|| pathInfo.contains("_login")
				|| pathInfo.startsWith("message") 
				|| pathInfo.startsWith("bbs_initData") 
				|| pathInfo.startsWith("netc")
				|| pathInfo.endsWith("logon.jsp")
				|| pathInfo.endsWith("login.jsp")
				|| pathInfo.endsWith("exit.asp")
				|| pathInfo.endsWith("getFixNumberSources.asp")
				|| pathInfo.endsWith("getAllSources.asp")
				|| pathInfo.endsWith("read.asp")
				|| pathInfo.endsWith("getMoreSources.asp")) {
			filterChain.doFilter(servletRequest, servletResponse);
		} else if (request.getSession().getAttribute(Constant.USER) == null) {
			if (pathInfo.startsWith("admin")) {
				response.getWriter().write("<script>alert('尚未登录！');top.location.href='"+ basePath +"/webpage/logon.jsp'</script>");
			} else if(pathInfo.startsWith("teacher") || pathInfo.startsWith("student")){
				response.getWriter().write("<script>alert('尚未登录！');top.location.href='"+ basePath +"/webpage/login.jsp'</script>");
			} else {
				response.getWriter().write("<script>alert('尚未登录！');top.location.href='/ITMS'</script>");
			}
		} else {
			filterChain.doFilter(servletRequest, servletResponse);
		}
	}

	@Override
	public void destroy() {}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
//		String [] url = filterConfig.getInitParameter("Urls").split(";");
//		for (int i = 0; i < url.length; i++) {
//			urls.add(url[i]);
//		}
	}
}
